import * as fs from "fs";
import * as path from "path";

export default class Utils {
  static readDirectory(directory: string, scanSubDirectories: boolean = false, regularExpression: RegExp) {
    const result = {}
    const readDirectory2 = (childDir) => {
      fs.readdirSync(childDir).forEach((file) => {
        let fullPath = path.resolve(childDir, file);
        let isDirectory = false
        if (fs.statSync(fullPath).isDirectory()) {
          isDirectory = true
          if (scanSubDirectories) {
            readDirectory2(fullPath);
          }
        }
        fullPath = Utils.pathChange(fullPath)
        if (!regularExpression.test(fullPath) || isDirectory) return;
        result[fullPath.replace(directory, '.')] = fullPath;
      })
    }
    fs.readdirSync(directory).forEach((file) => {
      let fullPath = path.resolve(directory, file);
      let isDirectory = false
      if (fs.statSync(fullPath).isDirectory()) {
        isDirectory = true
        if (scanSubDirectories) {
          readDirectory2(fullPath);
        }
      }
      fullPath = Utils.pathChange(fullPath)
      if (!regularExpression.test(fullPath) || isDirectory) return;
      result[fullPath.replace(directory, '.')] = fullPath;
    });
    return result
  }

  /**
   *   // for windows, the path.join will return with a path ending with a '/'
   *   // for linux/macos, the path.join will return with a path ending without '/'
   * @param basePath
   */
  static pathChange(basePath: string): string {
    basePath = basePath.replace(/\\/g, '/')
    if (basePath.endsWith('/')) {
      basePath = basePath.substring(0, basePath.length - 1)
    }
    return basePath
  }

}
